<template>
	<div class="container" style="height: 90%; background: #fff; padding: 10px 20px;">
		<view class="divider">
			<uni-icons type="undo-filled" size="20" class="top-left" @click="goBack">返回</uni-icons>
		</view>
		<div style="margin-top: 24px;">
			<label>抢修票模板：{{modelName}}</label>
			<div>
				<text><span style="color: red;font-size: 5rpx;">注意：*代表必填项，除字第名称及日期两项之外，其他项内容均支持自定义输入修改</span></text>
			</div>
			<div class="form-container">
				<div class="row">
					<div class="col-6">
						<span style="color: red;">*</span>
						<label>单位名称：</label>
						<view class="example-body">
							<uni-combox :candidates="companyList" placeholder="请选择单位" @input="onCompanyChange"
								v-model="startSchemeTemplate.comName" clearAble></uni-combox>
						</view>
					</div>
					<div class="col-6">
						<span style="color: red;">*</span>
						<label>字第名称：</label>
						<uni-data-select v-model="startSchemeTemplate.ticketName" :localdata="ticketOptions"
							@change="changTicket"
							:placeholder="startSchemeTemplate.ticketName==''?'请选择':startSchemeTemplate.ticketName"></uni-data-select>
					</div>
				</div>
				<div class="row">
					<div class="col-6">
						<span style="color: red;">*</span>
						<label>票单字第编号后四位：</label>
						<uni-combox :candidates="ticketNumList" v-model="ticketNum" placeholder="请选择后四位"
							class="inputArea" auto-height clearAble></uni-combox>
					</div>
					<div class="col-6">
						<span style="color: red;">*</span>
						<label>工作负责人：</label>
						<view class="example-body">
							<uni-combox :candidates="workersList" placeholder="请先选择单位"
								v-model="startSchemeTemplate.workLeader" clearAble></uni-combox>
						</view>
					</div>
				</div>
				<div class="row">
					<div class="col-6">
						<span style="color: red;">*</span>
						<label>工作班人员（不包括工作负责人)：</label>
						<robby-tags :data="workersList" v-model="workers" @add="addTag" @delete="delTag"
							:enable-del="true" :enable-add="true" bg-color-type="primary"></robby-tags>
					</div>
				</div>
				<div class="row">
					<div class="col-6">
						<span style="color: red;">*</span>
						<label>10kV线路名称：</label>
						<view class="example-body">
							<uni-combox :candidates="LineOptions" placeholder="请选择线路"
								v-model="startSchemeTemplate.lineName" clearAble></uni-combox>
						</view>
					</div>
					<div class="col-6">
						<span style="color: red;">*</span>
						<label>台区名称：</label>
						<view class="example-body">
							<uni-combox :candidates="platformList" placeholder="请选择台区" 
								v-model="startSchemeTemplate.platformName" clearAble></uni-combox>
						</view>
					</div>
					<div class="col-6" >
						<label>分支线名称：</label>
						<input v-model="startSchemeTemplate.branchName" placeholder="例:杜台四组支线" class="inputArea"
							auto-height></input>
					</div>
					<div class="col-6">
					  <span style="color: red;">*</span>
					  <label>高压杆号：</label>
					  <view class="pole-row">
					    <uni-combox
					      :candidates="poleNumber"
					      v-model="hpole.start"
						  @input="onHpoleChange"
					      placeholder="#01"
					      class="pole-input"
					      clearAble
					    />
					    <text class="divider">-</text>
					    <uni-combox
					      :candidates="poleNumber"
					      v-model="hpole.end"
						  @input="onHpoleChange"
					      placeholder="#02"
					      class="pole-input"
					      clearAble
					    />
					  </view>
					</div>
					<div class="col-6">
						<span style="color: red;">*</span>
						<label>低压几回线路标号：</label>
						<uni-combox :candidates="LineLabel" placeholder="例:D1、D2、D3"
							v-model="startSchemeTemplate.lLineLabel" clearAble></uni-combox>
					</div>
					<div v-if="startSchemeTemplate.template!=='' && startSchemeTemplate.template!='(操作票)配电倒闸操作票'"
						class="col-6">
						<span style="color: red;">*</span>
						<label>工作任务(内容)：</label>
						<uni-easyinput type="textarea" v-model="startSchemeTemplate.jobContent" placeholder="请输入工作内容" />
					</div>
					<div class="col-6" v-if="needLpole">
					  <label>低压杆号：</label>
					  <view class="pole-row">
					    <uni-combox
					      :candidates="poleNumber"
					      v-model="lpole.start"
						  @input="onLpoleChange"
					      placeholder="#01"
					      class="pole-input"
					      clearAble
					    />
					    <text class="divider">-</text>
					    <uni-combox
					      :candidates="poleNumber"
					      v-model="lpole.end"
						  @input="onLpoleChange"
					      placeholder="#02"
					      class="pole-input"
					      clearAble
					    />
					  </view>
					</div>
					<div class="col-6" v-if="needKnife">
						<label>开关刀闸选项：</label>
						<uni-data-select :localdata="knifeOptions"
						@change="changKnife"></uni-data-select>
					</div>
					<div class="col-6" v-if="ish3">
						<label>选择开关号和刀闸号</label>
						<uni-data-select v-model="startSchemeTemplate.kg[0]" :localdata="kgOptions"
							placeholder="开关号" ></uni-data-select>
						<uni-data-select v-model="startSchemeTemplate.dz[0]" :localdata="dzOptions"
							placeholder="刀闸号"  style="margin-top:1% ;"></uni-data-select>
					</div>
					<div class="col-6" v-if="ish4">
						<label>选择开关号和刀闸号</label>
						<uni-data-select v-model="startSchemeTemplate.kg[0]" :localdata="kgOptions"
							placeholder="开关号1" ></uni-data-select>
						<uni-data-select v-model="startSchemeTemplate.kg[1]" :localdata="kgOptions"
							placeholder="开关号2" style="margin-top:1% ;"></uni-data-select>
						<uni-data-select v-model="startSchemeTemplate.dz[0]" :localdata="dzOptions"
							placeholder="刀闸号1" style="margin-top:1% ;"></uni-data-select>
						<uni-data-select v-model="startSchemeTemplate.dz[1]" :localdata="dzOptions"
							placeholder="刀闸号2" style="margin-top:1% ;" ></uni-data-select>
					</div>
					<div class="col-6" v-if="ish8">
						<label>选择开关号</label>
						<uni-data-select v-model="startSchemeTemplate.kg[0]" :localdata="kgOptions"
							placeholder="开关号1" ></uni-data-select>
						<uni-data-select v-model="startSchemeTemplate.kg[1]" :localdata="kgOptions"
							placeholder="开关号2" style="margin-top:1% ;" ></uni-data-select>
					</div>
					<span style="color: red;">*</span>
					<text @click="changeTime">日期：</text>
					<uni-datetime-picker type="date" v-model="time" @change="changeTime" />
				</div>
			</div>
		</div>
		<div style="margin-bottom: 17px; text-align: left;">
			<button @click="exportWord"
				style="margin:57% 5% 5% 5%;background-color: deepskyblue;color: #fff;">导出模板</button>
		</div>
	</div>
</template>

<script>
	import docxtemplater from 'docxtemplater';
	import PizZip from 'pizzip';
	import path from 'path';
	import {
		parse,
		format
	} from 'date-fns';
	import robbyTags from '@/components/robby-tags/robby-tags.vue'
	import workersform from '@/data/company_user_mapping.json'
	import platform from '@/data/company_platform_mapping.json'
	import knifeform from '@/data/HighknifeMeasure_mapping.json'
	export default {
		data() {
			return {
				workers: [], //工作班人员（不包括工作负责人)
				startSchemeTemplate: {
					template: "", //文件模板名称
					/*以下数据与模板数据对应*/
					comName: "干河供电所", //单位名称
					ticketName: "", //字第名称
					ticketNumber: "", //票单字第编号
					groupName: "", //班组名称
					workLeader: "", //工作负责人
					// rushArranger: "", //抢修任务布置人**
					workerNames: "", //工作班人员（不包括工作负责人)
					workerNum: "", //工作班人员人数
					lineName: "", //线路名称
					platformName: "", //台区名称
					branchName: "", //分支线名称**
					lLineLabel: "", //低压几回线路标号**
					poleNumber: "", //高压杆号
					kg:[],//开关D1/D2/D3
					dz:[],//刀闸D16/D26/D36
					measure:[], //安全措施：拉开
					jobContent: "", //工作内容
					lpoleNumber: "", //低压杆号
					year: "", //年
					month: "", //月
					day: "", //日
				},
				hpole:{
					start:'',
					end:'',
				},
				lpole:{
					start:'',
					end:'',
				},
				time: "", //抢修年月日
				selected: 0,
				modelName: "", //模板名称
				kgOptions:[{value:"D1",text:"D1"},{value:"D2",text:"D2"},{value:"D3",text:"D3"}],
				dzOptions:[{value:"D16",text:"D16"},{value:"D26",text:"D26"},{value:"D36",text:"D36"}],
				ish3:false,	//是否是h3刀闸选项
				ish4:false, //是否是h4刀闸选项
				ish8:false, //是否是h8刀闸选项
				currentValue:'',//刀闸场景值
				needKnife: false, //是否需要选择开关刀闸
				needLpole: false, //干河是否需要填写低压杆号
				rangeOptions: [{
						value: "h1",
						text: "高压停电配变更换（停支线，使用吊车）",
						jobContent: "变压器故障处理（吊车更换变压器）",
						needKnife: true, //是否需要选择开关刀闸
						needLpole: false
					}, {
						value: "h2",
						text: "高压停电配变更换（停台区，使用叉车）",
						jobContent: "变压器故障处理（叉车更换变压器）",
						needKnife: true,
						needLpole: false
					}, {
						value: "h3",
						text: "高压停电配变更换（停台区，使用挖机）",
						jobContent: "变压器故障处理（挖机更换变压器）",
						needKnife: true,
						needLpole: true
					}, {
						value: "h4",
						text: "高压停电配变所属设备（如高低压线夹）",
						jobContent: "配变高压进线设备线夹、低压出线设备线夹故障更换",
						needKnife: true,
						needLpole: false
					}, {
						value: "h5",
						text: "高压停电更换集控柜及进出线（使用叉车）",
						jobContent: "集控柜及进出线烧毁故障处理（叉车更换集控柜及进出线）",
						needKnife: false,
						needLpole: true
					}, {
						value: "h6",
						text: "高压停电集控柜及进出线更换（使用链条葫芦等人力起重）",
						jobContent: "集控柜及进出线烧毁故障处理（使用葫芦更换集控柜及进出线）",
						needKnife: false, //是否需要选择开关刀闸
						needLpole: true
					}, {
						value: "h7",
						text: "高压停电电杆更换（吊车）",
						jobContent: "吊车更换电杆",
						needKnife: false, //是否需要选择开关刀闸
						needLpole: true
					}, {
						value: "h8",
						text: "高压停电电杆更换（挖机）",
						jobContent: "挖机更换电杆",
						needKnife: false, //是否需要选择开关刀闸
						needLpole: true
					}, {
						value: "h9",
						text: "高压停电树障清理",
						jobContent: "树障清除",
						needKnife: false, //是否需要选择开关刀闸
						needLpole: true
					}, {
						value: "h10",
						text: "高压停电导线故障处理（带收线）",
						jobContent: "B相断线故障抢修（导线连接、紧线）",
						needKnife: false, //是否需要选择开关刀闸
						needLpole: true
					},
					{
						value: "h11",
						text: "高压停电导线故障处理（不带收线）",
						jobContent: "B相导线脱落故障抢修（导线绑扎）",
						needKnife: false, //是否需要选择开关刀闸
						needLpole: true
					},{
						value: "h12",
						text: "高压停电瓷瓶更换",
						jobContent: "瓷瓶破裂故障处理(更换瓷瓶)",
						needKnife: false, //是否需要选择开关刀闸
						needLpole: true
					},{
						value: "h13",
						text: "高压停电熔断器更换",
						jobContent: "10kV跌落式熔断器故障抢修（更换熔断器）",
						needKnife: true, //是否需要选择开关刀闸
						needLpole: true
					},{
						value: "h14",
						text: "高压停电避雷器更换",
						jobContent: "变压器高压避雷器击穿故障处理（更换避雷器）",
						needKnife: true, //是否需要选择开关刀闸
						needLpole: true
					},{
						value: "h15",
						text: "高压停电母线及总空开更换",
						jobContent: "母线及0.4kV总空气开关更换",
						needKnife: false, //是否需要选择开关刀闸
						needLpole: true
					},
					{
						value: "h16",
						text: "高压停电返出线更换",
						jobContent: "返出线烧坏更换",
						needKnife: false, //是否需要选择开关刀闸
						needLpole: true
					},
					{
						value: "h17",
						text: "高压带电台区接火",
						jobContent: "绝缘斗臂车绝缘手套作业法带电接支接线路引线（配合低压电缆故障）",
						needKnife: false, //是否需要选择开关刀闸
						needLpole: true
					},
					{
						value: "h18",
						text: "高压带电台区解火",
						jobContent: "绝缘斗臂车绝缘手套作业法带电断支接线路引线（配合低压电缆故障）",
						needKnife: false, //是否需要选择开关刀闸
						needLpole: true
					}
				],
				//字第-班组数据
				ticketOptions: [{
					value: "l1",
					text: "配",
					groupName: "配电运检班"
				}, {
					value: "l2",
					text: "带",
					groupName: "配电带电作业班"
				}, {
					value: "l3",
					text: "外",
					groupName: "外勤班"
				}, {
					value: "l4",
					text: "外一",
					groupName: "外勤一班"
				}, {
					value: "l5",
					text: "外二",
					groupName: "外勤二班"
				}, {
					value: "l6",
					text: "外三",
					groupName: "外勤三班"
				}],
				//票单字第编号后四位
				ticketNum: "",
				ticketNumList: Array.from({
					length: 100
				}, (_, i) => `${(i + 1).toString().padStart(4, '0')}`),
				// 线路数据
				LineOptions:['安居线襄31', '八潭线长515', '百盛线江18', '北渠线襄48', '碧桂园线刘48', '扁花线敦13', '蔡邦线刘35', '蔡滩线童512', '曾台线长526', '昌盛线杜823', '陈河线童518', '城东线仙22', '城环线袁515', '城襄线袁516', '城镇二回线顺321', '城镇一回线顺315', '创业线襄23', '春天一回线襄12', '大柳湖线书512', '大兴二回线锋31', '德政线襄16', '电排河线环313', '东荆河线张17', '杜尧线曙光720', '敦柳线敦15', '范关线书513', '纺织线襄26', '分洪闸二回线龙华414', '分洪闸一回线龙华314', '锋德线锋15', '福星线仙53', '复州二回线锋33', '干河线襄17', '工业二回线海21', '工业线古河521', '工业线海20', '工业线江16', '工业线毛17', '工业线彭18', '工业线文15', '工业线新21', '工业线张14', '工业园线杨12', '共青园线杜813', '古堤线毛15', '古河二回线沔826', '古河一回线沔825', '官沟线环325', '官路线海13', '郭岭线郭14', '汉江线仙19', '翰林线仙59', '何帮线曙光724', '何口线曙光719', '何赵线彭17', '和合一回线杜825', '和平二回线瑞820', '河坝线长513', '恒天线刘49', '弘光线刘46', '红庙线古河512', '红垸线江11', '猴王线毛22', '胡口弦线文14', '胡镇线童511', '华亿二回线锋36', '华亿线锋22', '黄金河线仙58', '黄林线杜811', '黄水湖线彭28', '黄越线长520', '嘉华线彭13', '交通线文11', '茭排线下12', '解家口线彭25', '金台线刘15', '九合垸线顺325', '军垦二回线锋34', '军垦线锋12', '开发线仙17', '凯亚线仙15', '蓝天二回线刘34', '蓝天一回线刘31', '梨园线书518', '李台线环316', '立新线长525', '联丰线张15', '联合线新22', '练习场线襄59', '粮库二回线龙华415', '粮库一回线龙华315', '刘鼎线刘12', '刘杜一回刘53', '刘杜一回线杜814', '刘家垸线敦22', '刘仙二回线刘27', '刘仙一回线刘26', '刘仙一回线仙16', '柳沟线杜窑23', '柳集线长516', '剅镇线书519', '络绎线郑12', '屡丰线场14', '绿化线新23', '绿色家园四回线和平621', '麻港线童519', '毛场线潭17', '毛范垸线海15', '毛三线毛23', '梅湖线刘33', '沔洲线和平614', '纳河线杜窑14', '南国线襄56', '南湖线襄52', '南湖一回线瑞724', '南环线潭24', '排州线复732', '潘场线顺323', '潘口线杨14', '彭场线瑞818', '彭何线彭16', '坡场线顺324', '前通二回线刘52', '钱沟线龙华317', '秦杨线毛21', '仁和线锋30', '仁盛岭线杜窑12', '瑞刘二回线瑞825', '瑞刘一回线瑞725', '瑞阳线襄49', '三丰二回线锋42', '三丰线环314', '三号路二回线龙华413', '三号路一回线龙华313', '沙场二回线场18', '沙场一回线场13', '沙场一回线江13', '沙路线长524', '沙嘴线仙20', '邵沈渡线文13', '石垸线海16', '时代线和平520', '世纪线杜824', '市区二回线杨25', '市区二回线张19', '市区线古河522', '市区线海17', '市区线江12', '市区线毛18', '市区线彭24', '市区线文16', '市区线郑19', '市区一回线杨23', '市区一回线张21', '市镇线郑18', '丝宝二回线锋37', '丝宝线锋17', '四化线龙华318', '四居线环319', '四垸线古河513', '太子湖二回线瑞815', '太子湖三回线瑞816', '潭市线复707', '潭西线复714', '潭油线复724', '塘林线杨13', '塘湾线下13', '桃源线毛24', '腾飞线童522', '天合线杨22', '天星线海14', '通顺河线环312', '同兴线郑15', '团结线郑14', '万矩线环315', '王剅线张16', '王市口线刘19', '五湖一回线东耳13', '五莲线敦16', '西泵线曙光721', '西圻线曙光623', '西桥二回线锋35', '西桥线锋23', '西镇线曙光722', '下查线下14', '下查一回线和平511', '夏场线书516', '夏市线潭21', '仙杜线仙11', '仙发线新15', '仙光线潭13', '鲜码线潭14', '襄河二回线龙华412', '襄河一回线龙华312', '襄仙线仙21', '襄仙线襄13', '祥生二回线锋29', '向阳线毛26', '小河线顺316', '小南线环311', '肖台线襄32', '肖湾线仙51', '谢北线书611', '谢南线书517', '新街二回仙56', '新街一回仙55', '新里仁口线襄24', '新民一回线沔821', '新一中线仙50', '许坝线环318', '旭光线童520', '雅园线襄42', '沿河二回线锋32', '沿河线锋21', '阳光线古河520', '杨场线顺322', '杨丰线杨15', '杨岗线刘16', '杨岗一回线杜19', '杨挖线彭21', '杨越线毛14', '杨庄一回沔816', '姚咀线顺314', '叶王线杜812', '尤拔线江15', '余吉线刘30', '渔麻线渔18', '渔南线渔20', '渔业线郭22', '渔中线渔21', '御湖二回线襄58', '御湖一回线襄57', '御台线襄44', '裕波线龙华416', '园区线童513', '月亮湾二回线龙华411', '月亮湾一回线龙华311', '杂坝线襄43', '张场线新14', '长镇线长519', '镇商二回线顺320', '镇商一回线顺317', '郑家村线郑24', '中邦线江14', '中岭线彭11', '中铁三部线毛16', '周三线敦20', '洲岭线文21', '珠玑线毛12'],
				//高压杆号数据1-40
				poleNumber: Array.from({
					length: 40
				}, (_, i) => `#${(i + 1).toString().padStart(2, '0')}`),
				//低压几回线路标号数据
				LineLabel: ['D1', 'D2', 'D3'],
				//供电所-台区映射
				PlatOptions: platform,
				//供电所-工作班成员映射
				workersOptions: workersform,
				//开关刀闸映射,对应数组为this.startSchemeTemplate.measure
				knifeMeasure:knifeform,
				companyList: [],
				platformList: [],
				workersList: [],
				//开关刀闸选择 安全措施
				knifeOptions: [{
					value: "h1",
					text: "刀闸1个"
				}, {
					value: "h2",
					text: "刀闸2个"
				}, {
					value: "h3",
					text: "开关、刀闸各1个"
				}, {
					value: "h4",
					text: "开关、刀闸各2个"
				}, {
					value: "h5",
					text: "开关、刀闸各3个"
				}, {
					value: "h6",
					text: "开关、刀闸各3个、总刀闸1个"
				}, {
					value: "h7",
					text: "开关3个、总刀闸1个"
				},{
					value: "h8",
					text: "开关2个、总刀闸1个"
				}]
			}
		},
		onLoad(options) {
			const value = options.value; // 获取传递过来的参数
			console.log(value);
			this.changModel(value); 
		},
		created() {
			this.companyList = Object.keys(this.PlatOptions);
			this.workersList = this.workersOptions['干河供电所'];
			this.platformList = this.PlatOptions['干河供电所'];
			// console.log(this.PlatOptions['仙桃陈场供电所'])
		},
		watch: {
		 isReadyToReplace(newVal) {
		       if (newVal) {
		         console.log("kg 和 dz 已赋值完成，执行替换...");
		         this.updateMeasure();
		       }
		     }
		},
		computed: {
		    isReadyToReplace() {
		      // 当 kg 和 dz 都有值并且不为 undefined 或空字符串
			  if(this.startSchemeTemplate.kg.length === this.startSchemeTemplate.dz.length&&
			  this.startSchemeTemplate.kg.length!==0&&this.startSchemeTemplate.dz.length!==0){
			  	return true;
			  }
			  if(this.startSchemeTemplate.kg.length === 2 &&this.startSchemeTemplate.dz.length === 0){
			  	return true;
			  }
		    }
		  },
		methods: {
			goBack(){
				uni.navigateBack()
			},
			//删除人名
			delTag: function(e) {
				console.log(e.allTags.length);
				this.startSchemeTemplate.workerNum = e.allTags.length;
				this.startSchemeTemplate.workerNames = this.workerItems();
			},
			//添加
			addTag: function(e) {
				this.startSchemeTemplate.workerNum = e.allTags.length;
				console.log(e, this.startSchemeTemplate.workerNum);
				this.startSchemeTemplate.workerNames = this.workerItems();
				console.log(this.startSchemeTemplate.workerNames)
			},
			// 计算属性将数组元素用顿号连接起来
			workerItems() {
				return this.workers.join('、');
			},
			onHpoleChange(selectNumber){
				  // 使用箭头函数确保this指向正确
				      this.$nextTick(() => {
				        const { start, end } = this.hpole;
				        
				        if (start && end) {
				          this.startSchemeTemplate.poleNumber = start === end 
				            ? start 
				            : `${start}~${end}`;
				        } else {
				          // 处理只填写了一个的情况
				          this.startSchemeTemplate.poleNumber = start || end || '';
				        }
				        
				        // 这里可以添加后续处理，比如提交到父组件或触发其他操作
				        // console.log('生成的杆号字符串:', this.startSchemeTemplate.poleNumber);
				      });
			},
			onLpoleChange(selectNumber){
				  // 使用箭头函数确保this指向正确
				      this.$nextTick(() => {
				        const { start, end } = this.lpole;
				        
				        if (start && end) {
				          this.startSchemeTemplate.lpoleNumber = start === end 
				            ? start 
				            : `${start}~${end}`;
				        } else {
				          // 处理只填写了一个的情况
				          this.startSchemeTemplate.lpoleNumber = start || end || '';
				        }
				        
				        // 这里可以添加后续处理，比如提交到父组件或触发其他操作
				        // console.log('生成的杆号字符串:', this.startSchemeTemplate.lpoleNumber);
				      });
			},
			// 当供电所选择发生变化时，更新台区列表和工作班人员列表
			onCompanyChange(selectedCompany) {
				this.platformList = this.PlatOptions[selectedCompany] || [];
				this.workersList = this.workersOptions[selectedCompany] || [];
				// console.log(this.workersList)
				// 重置之前的台区选择
				this.startSchemeTemplate.platformName = "";
				// console.log(this.platformList)
			},
			// 选择时间
			changeTime(e) {
				console.log("时间", e);
				const date = parse(e, 'yyyy-MM-dd', new Date());
				this.startSchemeTemplate.year = format(date, 'yyyy');
				this.startSchemeTemplate.month = format(date, 'MM');
				this.startSchemeTemplate.day = format(date, 'dd');
				console.log(
					`Year: ${this.startSchemeTemplate.year}, Month: ${this.startSchemeTemplate.month}, Day: ${this.startSchemeTemplate.day}`
				);
				this.startSchemeTemplate.ticketNumber =
					`${this.startSchemeTemplate.year}${this.startSchemeTemplate.month}${this.ticketNum}`;
				console.log(this.ticketNum, this.startSchemeTemplate.ticketNumber);
			},
			//选择模板
			changModel(value) {
				const selectedItem = this.rangeOptions.find(option => option.value === value);
				this.modelName = selectedItem.text;
				this.startSchemeTemplate.jobContent = selectedItem.jobContent;
				this.startSchemeTemplate.template = value;
				this.needKnife = selectedItem.needKnife;
				this.needLpole = selectedItem.needLpole;
				console.log(this.needKnife, "选择模板", this.modelName, this.startSchemeTemplate.jobContent);
			},
			//替换刀闸措施中的占位符
			ReplaceWord(arr,platformName,kglist,dzlist,value){
				var Strlist = []
				Strlist = arr.map((item, index) => {
					// 执行替换
					const replacedItem = item.replace(/\{platformName\}/g, platformName);
					return replacedItem;
				});
				if(value === 'h3' || value === 'h4' || value === 'h8')
				{
					switch(value){
						case 'h3':
							Strlist[0] = Strlist[0].replace('{kg}',kglist[0])
							Strlist[0] = Strlist[0].replace('{dz}',dzlist[0])
							Strlist[1] = Strlist[1].replace('{dz}',dzlist[0])
							Strlist[3] = Strlist[3].replace('{dz}',dzlist[0])
							break;
						case 'h4':
							Strlist[0] = Strlist[0].replace('{kg}',kglist[0])
							Strlist[0] = Strlist[0].replace('{kg}',kglist[1])
							Strlist[0] = Strlist[0].replace('{dz}',dzlist[0])
							Strlist[0] = Strlist[0].replace('{dz}',dzlist[1])
							Strlist[1] = Strlist[1].replace('{dz}',dzlist[0])
							Strlist[2] = Strlist[2].replace('{dz}',dzlist[1])
							Strlist[4] = Strlist[4].replace('{dz}',dzlist[0])
							Strlist[4] = Strlist[4].replace('{dz}',dzlist[1])
							break;
						case 'h8':
							Strlist[0] = Strlist[0].replace('{kg}',kglist[0])
							Strlist[0] = Strlist[0].replace('{kg}',kglist[1])
							Strlist[1] = Strlist[1].replace('{kg}',kglist[0])
							Strlist[2] = Strlist[2].replace('{kg}',kglist[1])
							break;
					}
				}
				return Strlist
			},
			//选择开关刀闸
			changKnife(value) {
				this.startSchemeTemplate.kg=[]
				this.startSchemeTemplate.dz=[]
				this.ish3 = false;
				this.ish4 = false;
				this.ish8 = false;
				this.currentValue = value;
				if(value !== 'h3' || value !== 'h4' || value !== 'h8'){
					this.updateMeasure()
				}
				switch(value){
				case 'h3':
					this.ish3 = true;
					this.ish4 = false;
					this.ish8 = false;
					break;
				case 'h4':
					this.ish3 = false;
					this.ish4 = true;
					this.ish8 = false;
					break;
				case 'h8':
					this.ish3 = false;
					this.ish4 = false;
					this.ish8 = true;
					break;
				}
			
			},
			updateMeasure() {
			    // 这里才真正执行替换
				console.log("dz:"+this.startSchemeTemplate.dz)
			    console.log("开始替换占位符...");
			    this.startSchemeTemplate.measure = this.ReplaceWord(
			      this.knifeMeasure[this.currentValue],
			      this.startSchemeTemplate.platformName,
			      this.startSchemeTemplate.kg,
			      this.startSchemeTemplate.dz,
			      this.currentValue
			    );
				console.log(this.startSchemeTemplate.measure)
			},
			//选择字第-班组
			changTicket(value) {
				const selectedItem = this.ticketOptions.find(option => option.value === value);
				this.startSchemeTemplate.ticketName = selectedItem.text;
				this.startSchemeTemplate.groupName = selectedItem.groupName;
				console.log(value, "选择字第-班组", this.startSchemeTemplate.ticketName, this.startSchemeTemplate.groupName);
			},
			create(filename, data) {
				return new Promise((resolve, reject) => {
					// #ifdef APP-PLUS
					plus.io.resolveLocalFileSystemURL(filename, (entry) => {
						entry.file((file) => {
							var fileReader = new plus.io.FileReader();
							fileReader.onloadend = (evt) => {
								var base64 = evt.target.result;
								if (!base64) {
									plus.nativeUI.toast("读取到空数据，请检查模板文件路径和内容！")
									console.error("读取到空数据，请检查模板文件路径和内容！");
									return;
								}
								// plus.nativeUI.toast("读取到的 Base64 数据长度："+ base64.length)
								console.log("读取到的 Base64 数据长度：", base64.length);
								const arrayBuffer = uni.base64ToArrayBuffer(
									base64); // 转换为 ArrayBuffer
								var zip = new PizZip(arrayBuffer);
								var doc = new docxtemplater(zip, {
									paragraphLoop: true,
									linebreaks: true,
								});
							// ✅ 正确处理数组
							const textArray = this.startSchemeTemplate.measure || [];
										
							const data = {
								...this.startSchemeTemplate,
								textArray
							};
							console.log("最终渲染数据", data);
							try {
							  doc.render(data);
							} catch (error) {
							  console.error('docxtemplater渲染错误:', error);
							  reject(error);
							  return;
							}

								var buf = doc.getZip().generate({
									type: "nodebuffer",
									compression: "DEFLATE",
								});
								plus.nativeUI.toast("导出文件成功", {
									background: "#ffa38c",
								});
								resolve(buf);
							};
							fileReader.onerror = (err) => {
								console.error(err);
								reject(err);
							};
							fileReader.readAsDataURL(file);
						});
					}, (err) => {
						console.log("发生了错误", err);
						reject(err);
					});
					// #endif
	
					// #ifdef H5
					// 如果在 H5环境中运行，直接拒绝或者提示不支持
					reject("当前环境不支持 HTML5+ API (plus)");
					// #endif
				});
			},
			save(data, fileName) {
				return new Promise((resolve, reject) => {
					// #ifdef APP-PLUS
					let base64Str = uni.arrayBufferToBase64(data);
					var index = base64Str.indexOf(',');
					base64Str = base64Str.slice(index + 1, base64Str.length);
					plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, function(fs) {
						fs.root.getFile(fileName, {
							create: true
						}, function(entry) {
							var fullPath = fs.root.fullPath + fileName;
							let systemInfo = uni.getSystemInfoSync();
							if (systemInfo.platform == 'android') {
								var Base64 = plus.android.importClass("android.util.Base64");
								var FileOutputStream = plus.android.importClass(
									"java.io.FileOutputStream");
								try {
									var out = new FileOutputStream(fullPath);
									var bytes = Base64.decode(base64Str, Base64.DEFAULT);
									out.write(bytes);
									out.close();
									resolve(fullPath);
								} catch (e) {
									console.log(e.message);
									reject(e);
								}
							} else if (systemInfo.platform == 'ios') {
								var NSData = plus.ios.importClass('NSData');
								var nsData = new NSData();
								nsData = nsData.initWithBase64EncodedStringoptions(base64Str, 0);
								if (nsData) {
									nsData.plusCallMethod({
										writeToFile: fullPath,
										atomically: true,
									});
									plus.ios.deleteObject(nsData);
								}
								resolve(fullPath);
							}
						});
					});
					// #endif
	
					// #ifdef H5
					reject("当前环境不支持 HTML5+ API (plus)");
					// #endif
				});
			},
			exportWord() {
				if (this.modelName == "") {
					uni.showToast({
						title: '请先选择模板',
						icon: 'error'
					});
				} else if (this.startSchemeTemplate.year == "") {
					uni.showToast({
						title: '请先选择日期',
						icon: 'error'
					});
				} else {
					this.startSchemeTemplate.ticketNumber =
						`${this.startSchemeTemplate.year}${this.startSchemeTemplate.month}${this.ticketNum}`;
					const wmodelName = this.startSchemeTemplate.template;
					var templateFile = `_www/static/${wmodelName}.docx`;
					plus.io.resolveLocalFileSystemURL(templateFile, (entry) => {
						console.log("静态文件路径：", entry.fullPath);
						// plus.nativeUI.toast("静态文件路径：" + entry.fullPath);
					}, (err) => {
						console.error("无法读取模板文件：", err);
						plus.nativeUI.toast("无法读取模板文件");
					});
					// plus.nativeUI.toast(this.startSchemeTemplate.template)
					// 创建一个表示当前日期的字符串，格式可以根据需要调整
					var currentDate = new Date();
					var year = currentDate.getFullYear();
					var month = ('0' + (currentDate.getMonth() + 1)).slice(-2); // 月份从0开始，所以要加1
					var day = ('0' + currentDate.getDate()).slice(-2);
	
					// 组合日期和模型名称
					var newFileName = year + "-" + month + "-" + day + "_" + this.modelName + ".docx";
					// #ifdef APP-PLUS
					this.create(templateFile, this.startSchemeTemplate).then(buffer => {
						this.save(buffer, newFileName).then(filename => {
							uni.openDocument({
								fileType: 'docx',
								filePath: filename,
								success: function(res2) {
									console.log('打开文档成功');
								},
								fail: function(err) {
									if (err.errCode == 1 || err.code == 1) {
										uni.showToast({
											title: `未找到能打开docx类型文件的手机应用`,
											icon: 'none'
										});
									}
									console.log(err);
								}
							});
						});
					});
					// #endif
	
					// #ifdef H5
					uni.showToast({
						title: '此功能只支持APP环境',
						icon: 'none'
					});
					// #endif
				}
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.form-container {
		height: 100%;
	}

	.col-6 {
		margin: 5px 0px;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}

	.inputArea {
		/* background-color: antiquewhite; */
		border: 1px solid #ccc;
		padding: 5px;
		border-radius: 4px;
	}
	.pole-row {
	  display: flex;
	  align-items: center;
	  flex-wrap: nowrap;
	}
	
	.pole-input {
	  width: 80px;
	  margin: 0 4px;
	}
	
	.divider {
	  font-size: 16px;
	  margin: 0 2px;
	}
</style>